package com.example.demo.netty.heartbeat.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;

import java.sql.SQLOutput;

public class ServerHandler extends SimpleChannelInboundHandler<String> {
    private int overTimes=0;

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String str) throws Exception {
        System.out.println("收到心跳："+str);
        channelHandlerContext.writeAndFlush("收到心跳");
        overTimes=0;
    }

    /**
     * 当心跳包超时未收到时IdleStateHandler类就会触发这个方法，增加一次超时计数
     * @param ctx 上下文
     * @param evt IdleStateHandler对象
     * @throws Exception
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        IdleStateEvent event =(IdleStateEvent) evt;

        // 根据超时与否计数
        switch (event.state()) {
            case READER_IDLE -> {
                overTimes++;
                System.out.println("读超时");
            }
            case WRITER_IDLE -> System.out.println("写超时");
            case ALL_IDLE -> System.out.println("读写超时");
            default -> {
            }
        }
        // 超时3次以上关闭连接,但是感觉不如直接设置3次得总和时间
        if(overTimes>3){
            System.out.println("心跳超时,连接关闭");
            ctx.writeAndFlush("超时关闭");
            ctx.close();
        }

    }
}
